﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Win32;

namespace PluginInstaller
{
    internal static class PInstallerProgram
    {
        public static readonly string SmartQuantPath;
        private static bool _silence;

        private static string GetSmartQuantPath()
        {
            var assemblies = Registry.ClassesRoot.OpenSubKey(@"Installer\Assemblies");
            if (assemblies != null)
            {
                var names = assemblies.GetSubKeyNames();
                var file = names.FirstOrDefault(n => n.EndsWith("SmartQuant.dll"));
                if (!string.IsNullOrEmpty(file))
                {
                    file = file.Replace('|', '\\');
                    return Path.GetDirectoryName(file);
                }
            }

            return @"c:\Program Files\SmartQuant Ltd\OpenQuant 2014\";
        }

        private static Assembly DomainOnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var assemblyName = new AssemblyName(args.Name);
            var path = Path.Combine(SmartQuantPath, assemblyName.Name + ".dll");
            if (File.Exists(path)) {
                return Assembly.LoadFile(path);
            }
            Console.WriteLine(@"Not Found: " + assemblyName.Name);
            return null;
        }

        static PInstallerProgram()
        {
            SmartQuantPath = GetSmartQuantPath();
            AppDomain.CurrentDomain.AssemblyResolve += DomainOnAssemblyResolve;
        }

        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length == 0) {
                return;
            }

            foreach (var s in args) {
                if (s == "/silence") {
                    _silence = true;
                }
            }

            var installer = new Installer(args.Last());
            if (_silence) {
                installer.Install();
            }
            else {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                var form = new InfoDialog { Installer = installer };
                Application.Run(form);
            }
        }
    }
}
